<!--上传个人信息弹窗-->
<template>
  <div>
    <el-dialog title="信息详情" v-model="dialogVisible" width="50%" :close-on-click-modal="false" @close="closeDialog" center>
      <div class="dialog-content">
        <el-form ref="ruleFormRef" :model="personnelInformation" label-position="right" label-width="100">
          <div class="dialog-title">人员基础信息</div>
          <div class="dialog-message">
            <div class="dialog-avatar">
              <!-- 上传头像 -->
              <!--这里不展示label 所以label-width为0-->
              <el-form-item prop="pictureId" label-width="0">
                <image-upload
                  :isShowTip="!disabled"
                  @handleUploadRequest="handleUploadRequest"
                  @pictureDownload="pictureDownload"
                  @handleRemove="handleRemove"
                  v-model:fileList="profilePicture"
                  :disabled="disabled"
                />
              </el-form-item>
            </div>
            <!--个人信息-->
            <div class="dialog-intro">
              <el-form-item
                label="姓名："
                prop="userName"
                :rules="[
                  { required: !disabled, message: '请选择姓名', trigger: 'blur' },
                  { max: 20, message: '姓名不可超过20个字', trigger: 'blur' },
                ]"
              >
                <div
                  v-if="!disabled"
                  :class="disabled ? 'personnel-input personnel-input-disabled' : 'personnel-input'"
                  @click="userNameClick"
                >
                  <span v-if="!personnelInformation.userName" class="input-personnelList">请选择姓名</span>
                  <el-tag v-else :closable="!disabled" class="input-item" type="info" @close="personnelDeletion">
                    {{ personnelInformation.userName }}
                  </el-tag>
                </div>
                <el-input v-else v-model="personnelInformation.userName" disabled />
              </el-form-item>
              <el-form-item
                label="员工编号："
                prop="userId"
                :rules="[{ required: !disabled, message: '请输入员工编号', trigger: 'blur' }]"
              >
                <el-input v-model="personnelInformation.userId" disabled />
              </el-form-item>
              <el-form-item
                label="性别："
                prop="gender"
                :rules="[{ required: !disabled, message: '请输入性别', trigger: 'blur' }]"
              >
                <el-select
                  :disabled="disabled"
                  style="width: 100%"
                  v-model="personnelInformation.gender"
                  placeholder="请选择性别"
                >
                  <el-option v-for="(item, index) in genderList" :key="index" :label="item" :value="item" />
                </el-select>
              </el-form-item>
              <el-form-item
                label="支部："
                prop="partyOrgName"
                :rules="[{ required: !disabled, message: '请输入支部', trigger: 'blur' }]"
              >
                <el-input v-model="personnelInformation.partyOrgName" :disabled="disabled" placeholder="请输入支部" />
              </el-form-item>
              <el-form-item
                label="公司："
                prop="companyName"
                :rules="[{ required: !disabled, message: '请输入公司', trigger: 'blur' }]"
              >
                <el-input v-model="personnelInformation.companyName" :disabled="disabled" placeholder="请输入公司" />
              </el-form-item>
              <el-form-item
                label="职务："
                prop="partyBranchPosition"
                :rules="[
                  { required: !disabled, message: '请输入职务', trigger: 'blur' },
                  { max: 20, message: '职务不可超过20个字', trigger: 'blur' },
                ]"
              >
                <el-input v-model="personnelInformation.partyBranchPosition" :disabled="disabled" placeholder="请输入职务" />
              </el-form-item>
              <el-form-item
                label="电话："
                prop="phone"
                :rules="[
                  { required: !disabled, message: '请输入电话', trigger: 'blur' },
                  { pattern: /^((1[3456789]\d{9}))$/, message: '请输入正确的手机号码!' },
                ]"
              >
                <el-input v-model="personnelInformation.phone" :disabled="disabled" placeholder="请输入电话" />
              </el-form-item>
              <el-form-item label="个人简介：" prop="briefIntroduction">
                <el-input v-model="personnelInformation.briefIntroduction" :disabled="disabled" placeholder="请输入个人简介" />
              </el-form-item>
            </div>
          </div>
          <div :class="disabled ? 'dialog-title' : 'dialog-title validation-prompt'">
            宣讲经验（含宣讲时间、宣讲主题、宣讲对象）
          </div>
          <!--这里不展示label 所以label-width为0-->
          <el-form-item
            prop="lectureExperience"
            label-width="0"
            :rules="[
              { required: !disabled, message: '请输入宣讲经验', trigger: 'blur' },
              { max: 200, message: '宣讲经验不可超过200个字', trigger: 'blur' },
            ]"
          >
            <el-input
              v-model="personnelInformation.lectureExperience"
              type="textarea"
              :rows="4"
              :disabled="disabled"
              placeholder="请输入宣讲经验"
            />
          </el-form-item>
          <!-- 编辑状态时 不展示处理意见 -->
          <div class="handling_suggestion" v-if="auditStatus !== 'edit'">
            <!-- 没有上一环节处理意见时 不展示 -->
            <el-form-item label="上一环节处理意见：" prop="opinion" label-width="130" v-if="personnelInformation.opinion">
              <el-input style="width: 300px" v-model="personnelInformation.opinion" disabled />
            </el-form-item>
            <!-- 处理状态时, 可以编辑处理建议, 展示效验 -->
            <el-form-item
              v-if="auditStatus === 'handle'"
              label="处理意见："
              prop="currentOpinion"
              label-width="130"
              :rules="[
                { required: auditStatus === 'handle', message: '请输入处理意见', trigger: 'blur' },
                { max: 200, message: '处理意见不可超过200个字', trigger: 'blur' },
              ]"
            >
              <el-input
                style="width: 300px"
                v-model="personnelInformation.currentOpinion"
                :disabled="auditStatus === 'view'"
                placeholder="请输入处理意见"
              />
            </el-form-item>
          </div>
        </el-form>
      </div>
      <template #footer>
        <div style="margin-bottom: 20px">
          <div v-if="!disabled">
            <el-button type="primary" @click="handleInformationAction('informationSave')">保存</el-button>
            <el-button type="success" @click="handleInformationAction('informationSubmit')">提交</el-button>
            <el-button @click="dialogVisible = false">关闭</el-button>
          </div>
          <!-- 只有处理时 才可以展示审核按钮 -->
          <div v-if="disabled && auditStatus === 'handle'">
            <el-button type="primary" @click="reviewAndSubmit('审核通过', 'pass')">审核通过</el-button>
            <el-button @click="reviewAndSubmit('审核退回', 'sendBack')">审核退回</el-button>
            <el-button @click="dialogVisible = false">关闭</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
    <!--支部选择弹窗-->
    <PersonnelSelection
      ref="personnelSelectionDialog"
      @submit="personalInformation"
      :maxCount="maxCount"
      :personnel-or-branch="personnelOrBranch"
      :personnelEcho="personnelEcho"
    ></PersonnelSelection>
  </div>
</template>

<script setup>
import ImageUpload from "@/components/ImageUpload/index.vue";
import { ref } from "vue";
import { talentPoolUpload, showAttachmentDownload, attachmentEcho, queryUsers } from "@/api/navigationLecture";
import { ElMessage } from "element-plus";
import { fileBlobDownload } from "@/utils/fileDownload";
import PersonnelSelection from "@/components/flowDemo/PersonnelSelectionDialog.vue";
import { isEmpty } from "lodash";
import Conf from "@/utils/conf";
const { proxy } = getCurrentInstance();
const emit = defineEmits();
const props = defineProps({
  // 是否禁用
  disabled: {
    type: Boolean,
    default: false,
  },
  // 编辑人员信息数据列表
  editInformation: {
    type: Object,
    default: {},
  },
  // 审核状态 view: 查看, handle: 处理, edit: 编辑
  auditStatus: {
    type: String,
    default: "view",
  },
});
const dialogVisible = ref(false); // 弹窗显示隐藏
const ruleFormRef = ref(); // 弹窗表单ref
const pictureUrl = ref(""); // 头像url
// 弹窗表单人员信息
const personnelInformation = ref({
  id: "",
  userId: "",
  pictureId: "",
  pictureName: "",
  userName: "",
  gender: "",
  companyName: "",
  partyOrgName: "",
  partyBranchPosition: "",
  phone: "",
  briefIntroduction: "",
  lectureExperience: "",
  opinion: "", // 上一个环节处理意见
  currentOpinion: "", // 当前处理意见
});
const profilePicture = ref([]); // 头像上传列表
const genderList = ref(["男", "女"]); // 性别列表
const personnelSelectionDialog = ref(); // 支部选择弹窗的ref值
const personnelOrBranch = ref(""); // 获取人员
const personnelEcho = ref([]); // 人员回显列表
const isNeedMaxCount = ref(true); // 是否需要最大数量
watch(
  () => props.editInformation,
  (newVal) => {
    // 监听编辑信息列表 如果有数据 进行弹窗数据赋值
    if (newVal) {
      personnelInformation.value = newVal;
      // 如果有图片id则进行图片回显 没有则默认图片
      newVal?.pictureId ? avatarEcho(newVal) : setProfilePicture(newVal);
    }
  },
);
/**
 * 获取员工头像
 */
const setProfilePicture = (value) => {
  // 图片地址 如果有返回默认图片地址则进行图片回显 没有则展示本地默认图片
  profilePicture.value = isEmpty(value)
    ? []
    : [{ url: value?.imageUrl || Conf.VITE_DEFAULT_AVATAR_URL + value?.ygId, name: "员工头像.jpg" }];
};
/**
 * 提交审核
 */
const reviewAndSubmit = (value, type) => {
  proxy.$refs.ruleFormRef.validate((valid) => valid && submitForReview(value, type));
};
/**
 * 审核通过/不通过
 * @param value
 * @param type
 */
const submitForReview = (value, type) => {
  const { id, currentOpinion } = personnelInformation.value;
  // 提交审核数据
  const data = {
    id, // 提交工单id
    value, // 审核通过/退回
    type, // 审核接口类型
    currentOpinion, // 审核意见
  };
  emit("submitForReview", data);
};
/**
 * 头像回显
 * @param newVal 当前行数据
 */
const avatarEcho = async (newVal) => {
  try {
    const data = await attachmentEcho({ id: newVal.pictureId });
    const blob = new Blob([data], { type: "text/plain;charset=utf-8" });
    const URL = window.URL.createObjectURL(blob); // 创建一个指向该 Blob 对象的URL
    // 图片回显 图片列表为数组 单文件上传默认只有一个对象 获取到图片地址和名称进行赋值
    profilePicture.value = [{ url: URL, name: newVal?.pictureName }];
  } catch (error) {
    profilePicture.value = []; // 清空图片列表
    ElMessage.error(error);
  }
};
/**
 * 上传头像
 * @param item
 */
const handleUploadRequest = async (item) => {
  try {
    const formData = new FormData();
    formData.append("file", item.file); // 文件列表
    const { data } = await talentPoolUpload("talentPool", formData);
    personnelInformation.value.pictureId = data.id; // 头像id
    personnelInformation.value.pictureName = item.file.name; // 头像名称
    pictureUrl.value = data.url; // 头像url地址
    profilePicture.value.push(item.file);
    ElMessage.success("头像上传成功");
  } catch (error) {
    profilePicture.value = []; // 上传失败清除图片列表
    throw new Error(error);
  } finally {
    proxy.$modal.closeLoading();
  }
};
/**
 * 图片下载
 */
const pictureDownload = async () => {
  try {
    proxy.$modal.loading("请稍后...");
    // 图片下载 如果没有头像url地址 则用图片id进行图片回显接口下载
    const data = pictureUrl.value
      ? await showAttachmentDownload(pictureUrl.value)
      : await attachmentEcho({ id: personnelInformation.value.pictureId });
    // 图片下载 获取blob 图片为单文件上传 默认只有一个对象 从第一个里面取值图片名称
    fileBlobDownload(data, profilePicture.value[0].name);
    ElMessage.success("头像下载成功");
  } catch (error) {
    throw new Error(error);
  } finally {
    proxy.$modal.closeLoading();
  }
};
/**
 * 删除图片
 */
const handleRemove = async () => {
  //清空图片列表和图片id
  profilePicture.value = [];
  personnelInformation.value.pictureId = "";
};
/**
 * 弹窗提交保存
 */
const handleInformationAction = (action) => {
  // 弹窗数据效验
  proxy.$refs.ruleFormRef.validate((valid) => valid && emit(action, personnelInformation.value));
};
/**
 * 新增打开弹窗
 */
const addShow = async () => {
  dialogVisible.value = true; // 打开弹窗
  proxy.resetForm("ruleFormRef"); // 清空表单信息
};
/**
 * 编辑打开弹窗
 */
const editShow = () => {
  proxy.$refs?.ruleFormRef?.clearValidate(); // 清除校验
};
/**
 * 关闭弹窗的回调
 */
const closeDialog = () => {
  // 关闭后清空图片列表 否则下一次打开弹窗有缓存问题
  profilePicture.value = [];
};
/**
 * 人员弹窗
 */
// 人员选择最大数量,默认1人
const maxCount = ref(1);
/**
 * 人员信息赋值封装
 * @param name 人员姓名/支部名称
 * @param id 人员id/支部id
 * @param userSelect 返回的人员数据列表
 */
const userSelectAssign = (name, id, userSelect) => {
  personnelInformation.value[name] = userSelect?.label || "";
  personnelInformation.value[id] = userSelect?.ygId || "";
};
/**
 * 弹窗人员姓名点击事件
 */
const userNameClick = () => {
  personnelOrBranch.value = "personnel"; // 人员选择类型
  personnelSelectionDialog.value.showDialog(true); // 打开人员选择弹窗
  const { userName, partyOrgName, userId } = personnelInformation.value;
  // 如果有默认人员 则进行人员回显 当前是单选 所以只返回给一条数据
  personnelEcho.value = !userName ? [] : [{
    label: userName,
    orgShortName: partyOrgName,
    ygId: userId
  }]
};
// 人员选择框选人 确认后返回人员数据
const personalInformation = (data) => {
  // 人员信息只能单选 所以只返回一条数据 默认从第一个里面取值
  const userSelect = data[0];
  userSelectAssign("userName", "userId", userSelect);
  setProfilePicture(userSelect); // 获取员工头像
  getBranchInformation(userSelect.ygId); // 获取部门信息
};
/**
 * 获取部门信息
 * @param id 人员id
 */
const getBranchInformation = async (id) => {
  try {
    proxy.$modal.loading("请稍后...");
    // 通过人员id获取部门信息
    const { data } = await queryUsers(id);
    // 获取到支部信息和公司信息
    const {
      orgName: partyOrgName,
      orgUUID: partyOrgDn,
      companyName,
      companyDn,
      gender,
      administrativeDuties: partyBranchPosition,
      mobile: phone,
    } = data.data;
    const list = { partyOrgName, partyOrgDn, companyName, companyDn, gender, partyBranchPosition, phone };
    // 添加到人员信息列表中
    Object.assign(personnelInformation.value, list);
  } catch (error) {
    ElMessage.warning("未获取到党员信息");
  } finally {
    proxy.$modal.closeLoading();
  }
};
/**
 * 人员删除
 */
const personnelDeletion = () => {
  // 删除人员时 只清空人员信息
  userSelectAssign("userName", "userId");
  // 如果没有头像id 则清空图片列表
  if (!personnelInformation.value.pictureId) {
    profilePicture.value = [];
  }
};
defineExpose({
  addShow,
  editShow,
  dialogVisible,
});
</script>

<style scoped lang="less">
// 弹窗
:deep(.dialog-content) {
  padding: 10px 80px 30px;
  .el-form-item__label {
    font-size: 14px;
    font-weight: 500;
    width: 110px !important;
  }
  .dialog-title {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 20px;
  }
  .validation-prompt {
    &::before {
      content: "*";
      position: relative;
      top: -2px;
      left: 0;
      transform: translate(-50%, -50%);
      font-size: 13.5px;
      color: #f56c6c;
    }
  }
  .dialog-message {
    display: flex;
    justify-content: space-between;
    margin: 20px 0 30px;
    .dialog-avatar {
      width: 40%;
    }
    .dialog-intro {
      width: 60%;
      // 人员选择输入框
      .personnel-input {
        width: 100%;
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        border: 1px solid #dddfe6;
        border-radius: 5px;
        padding: 0 10px;
        cursor: pointer;
        min-height: 35px;
        .input-personnelList {
          color: #a9abb2;
          font-size: 14px;
        }
      }
      .personnel-input-disabled {
        background-color: #f5f7fa;
        cursor: not-allowed;
      }
    }
  }
  // 处理意见
  .handling_suggestion {
    margin-top: 50px;
    display: flex;
    flex-direction: column;
    align-items: center;
  }
}
// 头像样式
.none-up :deep(.el-upload--picture-card) {
  display: none;
}
</style>
